package com.tt.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tt.reggie.common.BaseContext;
import com.tt.reggie.common.R;
import com.tt.reggie.entity.Category;
import com.tt.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R<String> addFoodType(@RequestBody Category category, HttpServletRequest request){
        Long empId = (Long) request.getSession().getAttribute("employee");
        BaseContext.setCurrentId(empId);
        categoryService.save(category);
        return R.success("添加菜品成功");
    }

    @GetMapping("/page")
    public R<Page> pageR(int page,int pageSize){
        //分页构造器
        Page<Category> pageInfo = new Page<>(page,pageSize);

        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        lambdaQueryWrapper.orderByAsc(Category::getSort);

        categoryService.page(pageInfo,lambdaQueryWrapper);


        return R.success(pageInfo);
    }

    @DeleteMapping
    public R<String> delete(long ids){
       //删除分类
        boolean isDelete = categoryService.remove(ids);
        if(isDelete){
            return R.success("删除成功！");
        }

        return R.error("删除失败！");
    }


    @PutMapping
    public R<String> update(@RequestBody Category category,HttpServletRequest httpServletRequest){
        long empId = (long)httpServletRequest.getSession().getAttribute("employee");
        BaseContext.setCurrentId(empId);

        boolean updateById = categoryService.updateById(category);


        if(updateById){
            return R.success("修改分类信息成功！");
        }

        return R.error("修改分类信息失败！");
    }

    @GetMapping("/list")
    public R<List<Category>> selectAllList(Category category){
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        lambdaQueryWrapper.eq(category.getType()!=null,Category::getType,category.getType());
        lambdaQueryWrapper.orderByAsc(Category::getSort).orderByAsc(Category::getUpdateTime);
        List<Category> list = categoryService.list(lambdaQueryWrapper);

        return R.success(list);
    }

}
